import numpy as np

def convert_b_matrix_row_to_col_major(input_file, output_file, rows=16, cols=8):
    """
    将行优先的B矩阵转换为列优先格式（纯字符串转置，不做数值转换）
    
    Args:
        input_file: 输入文件路径（行优先格式）
        output_file: 输出文件路径（列优先格式）
        rows: B矩阵的行数（k_size）
        cols: B矩阵的列数（n_size）
    """
    print(f"字符串转置B矩阵: {rows}x{cols} 行优先 -> 列优先")
    
    # 读取输入文件，去除空白行
    with open(input_file, 'r') as f:
        data = [line.strip() for line in f if line.strip()]
    
    print(f"读取到 {len(data)} 个数据点")
    
    # 检查数据数量是否正确
    expected_count = rows * cols
    if len(data) != expected_count:
        print(f"警告: 数据数量不匹配，期望 {expected_count}，实际 {len(data)}")
        # 如果数据不足，用'0'填充
        while len(data) < expected_count:
            data.append('0')
        # 如果数据过多，截断
        data = data[:expected_count]
    
    # 重塑为矩阵（行优先）
    matrix = np.array(data).reshape(rows, cols)
    
    print("原始矩阵（行优先）前几行:")
    for i in range(min(4, rows)):
        print(f"行{i}: {matrix[i][:8].tolist()}...")
    
    # 转置为列优先顺序
    col_major_data = []
    for col in range(cols):
        for row in range(rows):
            col_major_data.append(matrix[row, col])
    
    # 写入输出文件
    with open(output_file, 'w') as f:
        for val in col_major_data:
            f.write(val + '\n')
    
    print(f"转换完成，输出到: {output_file}")
    print(f"列优先格式前16个值: {col_major_data[:16]}")
    
    # 验证转换正确性
    print("\n验证转换正确性:")
    # 重新读取并验证
    with open(output_file, 'r') as f:
        col_major_lines = [line.strip() for line in f.readlines() if line.strip()]
    
    # 重塑为列优先矩阵
    col_major_matrix = np.array(col_major_lines).reshape(cols, rows).T
    print("转换后的矩阵（列优先）前几列:")
    for j in range(min(4, cols)):
        print(f"列{j}: {col_major_matrix[:8, j].tolist()}...")
    
    return True

if __name__ == "__main__":
    # 示例：转换16x32的B矩阵
    input_file = "D:/FPGA/Full/TPU/SA/TPU/top/systolic_array/testbench/int4_int32/m8n32k16/b_int4_m8n32k16_hex.txt"
    output_file = "D:/FPGA/Full/TPU/SA/TPU/top/systolic_array/testbench/int4_int32/m8n32k16/b_int4_m8n32k16_col_major_hex.txt"
    
    convert_b_matrix_row_to_col_major(input_file, output_file, rows=16, cols=32) 